'use strict';
const uniID = require('uni-id')
const db = uniCloud.database();
const table='uni-id-users';
const dbCmd = db.command
const $ = db.command.aggregate
exports.main = async (event) => {
	
	// 云函数url，把body转为event所需？
	
	//把token也放进上传参数
	let body = event.body
	if(body){
		let token = event.headers.uniidtoken
		if(event.isBase64Encoded){
			body = Buffer.from(body)
		}
		const param = JSON.parse(body) // param为客户端上传的数据
		if(param){
			event = param
			event.uniIdToken = token
		}
	}
	
	let params = event.params || {}
	let res = {}
	let payload = {}
	//设置不检查token的类型
	let noCheckAction = ['register', 'checkToken', 'encryptPwd', 'login', 'loginByWeixin', 'sendSmsCode',
		'setVerifyCode', 'loginBySms', 'loginByEmail', 'code2SessionWeixin', 'code2SessionAlipay', 'checkUserName',
		'get'
	]
	if (noCheckAction.indexOf(event.action) === -1) {
		//如果没有token
		if (!event.uniIdToken) {
			return {
				code: 403,
				msg: '缺少token'
			}
		}
		//通过token去换取用户信息
		payload = await uniID.checkToken(event.uniIdToken)
		if (payload.code && payload.code > 0) {
			return payload
		}
		params.uid = payload.uid
	}
	
	switch (event.action) {
		case 'checkUserName':
			var username = params.username
			var collection = db.collection(table)
			var row = await collection.where({
				username:username
			}).limit(1).get()
			if(row.data.length<1){
				return {
					code:0,
					data:{
						code:200,
						message:"用户不存在"
					},
				}
			}
			return {
				code:0,
				data:{
					code:400,
					username:row.data[0].username
				},
			}
			break;
		case 'get':
			var id=event.id;
			var collection = db.collection(table)
			var row = await collection.where({
				_id:id
			}).limit(1).get();
			if(row.data.length<1){
				return {
					error:1,
					message:"数据不存在"
				}
			}
			return {
				error:0,
				data:{
					user:row.data[0]
				},
			};
			break;
		case 'register':
			res = await uniID.register(event.params);
			break;
		case 'login':
			res = await uniID.login({
				...event.params
			});
			break;
		case 'logout':
			res = await uniID.logout(event.uniIdToken);
			break;
		case 'updatePassword':
			res = await uniID.updatePwd(params);
			break;
		case 'setAvatar':
			res = await uniID.setAvatar(params);
			break;
		default:
			res = {
				code: 403,
				msg: '非法访问'
			}
			break;
	}

	//返回数据给客户端
	return res
};
